﻿using Fiddler;
using System;
using System.Net;
using System.Security;
using System.Text;

namespace FiddlerToJMeter
{
    public class HTTPSamplerProxy
    {
        private Session session;

        public string Xml
        {
            get
            {
                StringBuilder stringBuilder = new StringBuilder();
                string hTTPMethod = this.session.oRequest.headers.HTTPMethod;
                string host = this.session.host;
                string hostname = this.session.hostname;
                string port = this.Port;
                string text = this.session.id.ToString();
                string uriScheme = this.session.oRequest.headers.UriScheme;
                string text2 = WebUtility.UrlDecode(this.RequestBody);
                bool flag = text2.Contains("&");
                if (flag)
                {
                    text2 = this.RequestBody;
                }
                string arg = this.Path;
                string text3 = this.Path;
                string path = this.Path;
                string requestBody = this.RequestBody;
                string arg2 = "";
                string arg3 = "";
                bool flag2 = path.Contains("frameUrlSecretParam=");
                if (flag2)
                {
                    string[] array = path.Split(new string[]
                    {
                        "frameUrlSecretParam="
                    }, StringSplitOptions.None);
                    string str = array[0];
                    string encodedValue = array[1];
                    string s = System.Net.WebUtility.HtmlDecode(encodedValue);
                    string @string = Encoding.UTF8.GetString(Convert.FromBase64String(s));
                    arg2 = @string;
                    arg = str + "frameUrlSecretParam=${path_" + text + "}";
                }
                bool flag3 = requestBody.Contains("frameBodySecretParam=");
                if (flag3)
                {
                    string[] array2 = requestBody.Split(new string[]
                    {
                        "SecretParam="
                    }, StringSplitOptions.None);
                    string encodedValue2 = array2[1];
                    string encodedValue3 = System.Net.WebUtility.HtmlDecode(encodedValue2);
                    string s2 = System.Net.WebUtility.HtmlDecode(encodedValue3);
                    string string2 = Encoding.UTF8.GetString(Convert.FromBase64String(s2));
                    string text4 = System.Net.WebUtility.HtmlDecode(string2);
                    string text5 = text4.Replace("\\", "\\\\");
                    string str2 = text5.Replace("\"", "\\\"");
                    arg3 = SecurityElement.Escape(str2);
                    text2 = "frameBodySecretParam=${body_" + text + "}";
                }
                bool flag4 = text3.Contains("?");
                if (flag4)
                {
                    text3 = text3.Substring(0, text3.IndexOf("?"));
                }
                string arg4 = string.Concat(new string[]
                {
                    text,
                    "-",
                    uriScheme,
                    "://",
                    host,
                    text3
                });
                string arg5 = uriScheme + "://" + host + this.Path;
                bool flag5 = this.session.oFlags.ContainsKey("ui-comments");
                bool flag6 = flag5;
                if (flag6)
                {
                    string text6 = this.session.oFlags["ui-comments"].Trim();
                    bool flag7 = !text6.Contains("[#") && text6 != null && !(text6 == "");
                    if (flag7)
                    {
                        arg4 = string.Concat(new string[]
                        {
                            text,
                            "-",
                            text6,
                            "-",
                            uriScheme,
                            "://",
                            host,
                            text3
                        });
                    }
                }
                stringBuilder.Append(string.Format("<HTTPSamplerProxy guiclass=\"HttpTestSampleGui\" testclass=\"HTTPSamplerProxy\" testname=\"{0}\" enabled=\"true\">", arg4));
                stringBuilder.Append("<boolProp name=\"HTTPSampler.postBodyRaw\">true</boolProp>");
                stringBuilder.Append("<elementProp name=\"HTTPsampler.Arguments\" elementType=\"Arguments\">");
                stringBuilder.Append("<collectionProp name=\"Arguments.arguments\">");
                stringBuilder.Append("<elementProp name=\"\" elementType=\"HTTPArgument\">");
                stringBuilder.Append("<boolProp name=\"HTTPArgument.always_encode\">false</boolProp>");
                bool flag8 = this.session.oRequest.headers.Exists("Content-Type");
                bool flag9 = flag8;
                if (flag9)
                {
                    bool flag10 = this.session.RequestHeaders["Content-Type"].Contains("multipart/form-data; boundary");
                    if (flag10)
                    {
                        stringBuilder.Append(string.Format("<stringProp name=\"Argument.value\">{0}</stringProp>", "错误：上传请求无法进行转换，请手动编辑"));
                    }
                    else
                    {
                        stringBuilder.Append(string.Format("<stringProp name=\"Argument.value\">{0}</stringProp>", text2));
                    }
                }
                else
                {
                    stringBuilder.Append(string.Format("<stringProp name=\"Argument.value\">{0}</stringProp>", text2));
                }
                stringBuilder.Append("<stringProp name=\"Argument.metadata\">=</stringProp>");
                stringBuilder.Append("</elementProp>");
                stringBuilder.Append("</collectionProp>");
                stringBuilder.Append("</elementProp>");
                stringBuilder.Append(string.Format("<stringProp name=\"HTTPSampler.domain\">{0}</stringProp>", hostname));
                stringBuilder.Append(string.Format("<stringProp name=\"HTTPSampler.port\">{0}</stringProp>", port));
                stringBuilder.Append("<stringProp name=\"HTTPSampler.connect_timeout\"></stringProp>");
                stringBuilder.Append("<stringProp name=\"HTTPSampler.response_timeout\"></stringProp>");
                stringBuilder.Append(string.Format("<stringProp name=\"HTTPSampler.protocol\">{0}</stringProp>", uriScheme));
                stringBuilder.Append("<stringProp name=\"HTTPSampler.contentEncoding\">utf-8</stringProp>");
                stringBuilder.Append(string.Format("<stringProp name=\"HTTPSampler.path\">{0}</stringProp>", arg));
                stringBuilder.Append(string.Format("<stringProp name=\"HTTPSampler.method\">{0}</stringProp>", hTTPMethod.ToUpper()));
                stringBuilder.Append("<boolProp name=\"HTTPSampler.follow_redirects\">true</boolProp>");
                stringBuilder.Append("<boolProp name=\"HTTPSampler.auto_redirects\">false</boolProp>");
                stringBuilder.Append("<boolProp name=\"HTTPSampler.use_keepalive\">true</boolProp>");
                stringBuilder.Append("<boolProp name=\"HTTPSampler.DO_MULTIPART_POST\">false</boolProp>");
                stringBuilder.Append("<boolProp name=\"HTTPSampler.monitor\">false</boolProp>");
                stringBuilder.Append("<stringProp name=\"HTTPSampler.embedded_url_re\"></stringProp>");
                stringBuilder.Append(string.Format("<stringProp name=\"TestPlan.comments\">{0}</stringProp>", arg5));
                stringBuilder.Append("</HTTPSamplerProxy>");
                bool flag11 = true;
                bool flag12 = this.MyReferer == null || this.MyReferer.Length < 1;
                if (flag12)
                {
                    flag11 = false;
                }
                bool flag13 = this.session.oRequest.headers.Exists("X-Requested-With");
                bool flag14 = flag5 | flag11 | flag13;
                bool flag15 = flag14;
                if (flag15)
                {
                    stringBuilder.Append("<hashTree><HeaderManager guiclass=\"HeaderPanel\" testclass=\"HeaderManager\" testname=\"HTTP信息头管理器\" enabled=\"true\"><collectionProp name=\"HeaderManager.headers\">");
                    bool flag16 = flag11;
                    if (flag16)
                    {
                        stringBuilder.Append(string.Format("<elementProp name=\"\" elementType=\"Header\"><stringProp name=\"Header.name\">Referer</stringProp><stringProp name=\"Header.value\">{0}</stringProp></elementProp>", this.MyReferer));
                    }
                    bool flag17 = flag13;
                    if (flag17)
                    {
                        stringBuilder.Append(string.Format("<elementProp name=\"\" elementType=\"Header\"><stringProp name=\"Header.name\">X-Requested-With</stringProp><stringProp name=\"Header.value\">{0}</stringProp></elementProp>", this.session.RequestHeaders["X-Requested-With"]));
                    }
                    bool flag18 = flag5;
                    if (flag18)
                    {
                        stringBuilder.Append(string.Format("<elementProp name=\"\" elementType=\"Header\"><stringProp name=\"Header.name\">Content-Type</stringProp><stringProp name=\"Header.value\">{0}</stringProp></elementProp>", this.session.RequestHeaders["Content-Type"]));
                    }
                    stringBuilder.Append("</collectionProp></HeaderManager>");
                }
                stringBuilder.Append("<hashTree/>");
                bool flag19 = path.Contains("frameUrlSecretParam=");
                if (flag19)
                {
                    stringBuilder.Append(string.Format("          <JSR223PreProcessor guiclass=\"TestBeanGUI\" testclass=\"JSR223PreProcessor\" testname=\"JSR223 预处理程序\" enabled=\"true\">\r\n            <stringProp name=\"cacheKey\">true</stringProp>\r\n            <stringProp name=\"filename\"></stringProp>\r\n            <stringProp name=\"parameters\"></stringProp>\r\n            <stringProp name=\"script\">//path参数\r\nString decodedPath =&quot;{0}&quot;;\r\n\r\n//path参数编码\r\nString encodePath1 =Base64.getEncoder().encodeToString(decodedPath.getBytes());\r\nString encodePath2 =URLEncoder.encode(encodePath1, &quot;UTF-8&quot;);\r\nvars.put(&quot;path_{2}&quot;,encodePath2);\r\n\r\n\r\n//body参数\r\nString decodedBody =&quot;{1}&quot;;\r\n\r\n//body参数编码 \r\nString encodeBody1 = URLEncoder.encode(decodedBody, &quot;UTF-8&quot;);\r\nString encodeBody2 = Base64.getEncoder().encodeToString(encodeBody1.getBytes());\r\nString encodeBody3 = URLEncoder.encode(encodeBody2, &quot;UTF-8&quot;);\r\nvars.put(&quot;body_{2}&quot;,encodeBody3);</stringProp>\r\n            <stringProp name=\"scriptLanguage\">java</stringProp>\r\n          </JSR223PreProcessor>\r\n          <hashTree/>", arg2, arg3, text));
                }
                bool flag20 = flag14;
                if (flag20)
                {
                    stringBuilder.Append("</hashTree>");
                }
                return stringBuilder.ToString();
            }
        }

        private string Path
        {
            get
            {
                return System.Net.WebUtility.HtmlDecode(this.session.PathAndQuery);
            }
        }

        private string Port
        {
            get
            {
                return this.getPort();
            }
        }

        private string RequestBody
        {
            get
            {
                return System.Net.WebUtility.HtmlDecode(this.session.GetRequestBodyAsString());
            }
        }

        private string MyReferer
        {
            get
            {
                return System.Net.WebUtility.HtmlDecode(this.session.RequestHeaders["Referer"]);
            }
        }

        public HTTPSamplerProxy(Session session)
        {
            this.session = session;
        }

        private string getPort()
        {
            int port = this.session.port;
            string uriScheme = this.session.oRequest.headers.UriScheme;
            bool flag = uriScheme.ToLower() == "https" && port == 443;
            string result;
            if (flag)
            {
                result = "";
            }
            else
            {
                bool flag2 = uriScheme.ToLower() == "http" && port == 80;
                if (flag2)
                {
                    result = "";
                }
                else
                {
                    result = port.ToString();
                }
            }
            return result;
        }
    }
}
